package com.yld.car.market;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.BitmapUtils;
import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.Car;
import com.yld.car.domain.DealerBaseInfo;
import com.yld.car.domain.MyPublishCarInfo;
import com.yld.car.domain.UserInfo;

public class DealerMarketActivity extends BaseActivity implements
		OnItemClickListener {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.dealer_market_base_list);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);

		TextView titleTextView = ((TextView) findViewById(R.id.title));
		titleTextView.setText("经销商店铺");
		utils = NetworkProgressUtils.getInstance();
		showBackButton();
		this.progressBar = ((ProgressBar) findViewById(R.id.progressBar));
		this.progressBar.setVisibility(View.VISIBLE);

		list1 = (ListView) findViewById(R.id.list1);
		list2 = (ListView) findViewById(R.id.list2);
		list2.setOnItemClickListener(this);
		Intent intent = this.getIntent();
		bId = intent.getStringExtra("bId");
		shareSms = intent.getStringExtra("shareSms");
		if (shareSms == null) {
			shareSms = "暂无分享";
		}
		new DealerMarketInfoTask().execute(bId);
		new DealerMarketDetailTask().execute(bId);
	}

	private ProgressBar progressBar;
	private String bId;
	private String shareSms;
	private NetworkProgressUtils utils;
	private ListView list1;
	private ListView list2;

	private class DealerMarketAdapter extends BaseAdapter {

		public DealerMarketAdapter(Context mContext, DealerBaseInfo d) {

			this.mContext = mContext;
			this.mDealerBaseInfo = d;
		}

		private Context mContext;
		private DealerBaseInfo mDealerBaseInfo;

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 2;
		}

		@Override
		public Object getItem(int position) {

			return null;
		}

		@Override
		public long getItemId(int position) {

			return 0;
		}

		private void telDo(final String telNumber) {
			AlertDialog.Builder localBuilder = new AlertDialog.Builder(mContext);
			localBuilder.setTitle("拨打电话");
			localBuilder.setMessage(telNumber);
			localBuilder.setCancelable(false);
			localBuilder.setPositiveButton("呼叫",
					new DialogInterface.OnClickListener() {
						public void onClick(
								DialogInterface paramDialogInterface,
								int paramInt) {
							Intent localIntent = new Intent(
									"android.intent.action.CALL", Uri
											.parse("tel:" + telNumber));
							startActivity(localIntent);
						}
					});
			localBuilder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(
								DialogInterface paramDialogInterface,
								int paramInt) {
						}
					});
			localBuilder.create().show();
		}

		/**
		 * 分享短信
		 */
		private void shareToMessage(String msg, String target) {

			if (mDealerBaseInfo != null) {
				// StringBuffer sb = new StringBuffer();
				// // 品牌型号、价格、外内饰简称、状态、配置 就5个东西
				// sb.append("来自爱车行分享，您家的这款车源：" + carName + "/" + carSeries +
				// "/"
				// + mDealerBaseInfo.getPress() + "万/"
				// + mDetailInfoCar.getName() + "/" + carType + "/"
				// + mDetailInfoCar.getXppz());
				Intent localIntent = new Intent("android.intent.action.SENDTO",
						Uri.parse("smsto:" + target));
				localIntent.putExtra("sms_body", msg);
				startActivity(localIntent);
				finish();
			} else {
				Toast.makeText(mContext, "暂时无法完成短信分享", Toast.LENGTH_SHORT)
						.show();
			}

		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == 0) {

				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.contact_detail_items_header, null);

				ImageView imageView = (ImageView) convertView
						.findViewById(R.id.detailAvatar);

				String downloadUrl = "";
				String tmp = mDealerBaseInfo.getUserimg();
				if (tmp.indexOf("aodi") >= 0) {

					downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL_NEW + tmp;
				} else {
					downloadUrl = ConstantUtils.DOWNLOAD_IMAGE_URL + tmp;
				}

				BitmapUtils bitmapUtils = new BitmapUtils(
						getApplicationContext());

				// 加载网络图片
				bitmapUtils.display(imageView, downloadUrl);
				// imageView.setImageResource(android.R.drawable.ic_menu_add);
				TextView textView = (TextView) convertView
						.findViewById(R.id.detailName);
				textView.setText(mDealerBaseInfo.getCompname());

				// ImageView imageView1 = (ImageView) convertView
				// .findViewById(R.id.detailAuth);
				// imageView1.setImageResource(android.R.drawable.ic_menu_call);
				TextView textView1 = (TextView) convertView
						.findViewById(R.id.detailAddress);
				textView1.setText(mDealerBaseInfo.getAddress());

				Button b = (Button) convertView.findViewById(R.id.jianjie);
				b.setText(mDealerBaseInfo.getIntro());
				b.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent intent = new Intent();
						intent.setClass(mContext, DealerPageActivity.class);
						intent.putExtra("bId", bId);
						startActivity(intent);

					}
				});
				return convertView;
			} else if (position == 1) {

				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.contact_detail_items_action, null);

				Button telBtn = (Button) convertView
						.findViewById(R.id.telButton);

				telBtn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						telDo(mDealerBaseInfo.getTelephone());
					}
				});
				Button smsBtn = (Button) convertView
						.findViewById(R.id.smsButton);

				smsBtn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						// StringBuffer sb = new StringBuffer();
						// // 品牌型号、价格、外内饰简称、状态、配置 就5个东西
						// sb.append("来自爱车行分享，您家的这款车源：" + carName + "/" +
						// carSeries +
						// "/"
						// + mDealerBaseInfo.getPress() + "万/"
						// + mDetailInfoCar.getName() + "/" + carType + "/"
						// + mDetailInfoCar.getXppz());
						shareToMessage(shareSms, mDealerBaseInfo.getTelephone());

					}
				});

				final Button attentionBtn = (Button) convertView
						.findViewById(R.id.actionButton);

				UserInfo u = (UserInfo) readObject("userInfo");
				final boolean isMySelf = mDealerBaseInfo.getId().equals(
						u.getUserId());

				if ("0".equals(mDealerBaseInfo.getGuanzu())) {

					attentionBtn.setBackgroundResource(R.drawable.user_btn_3);
					isAttentionDealer = true;
				} else {
					attentionBtn.setBackgroundResource(R.drawable.user_btn_4);
					isAttentionDealer = false;
				}
				if (isMySelf) {
					attentionBtn.setBackgroundResource(R.drawable.user_btn_3);
				}
				attentionBtn.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						// shareToMessage(shareSms,
						// mDealerBaseInfo.getTelephone());

						if (isMySelf) {

							Toast.makeText(DealerMarketActivity.this,
									"不能关注自己！", Toast.LENGTH_SHORT).show();
							return;
						}
						if (isAttentionDealer) {

							attentionDealer(attentionBtn);

						} else {
							cancelAttentionDealer(attentionBtn);
						}

					}
				});
				return convertView;
			}

			return null;
		}

		private void attentionDealer(final Button btn) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					UserInfo u = (UserInfo) readObject("userInfo");

					String currentDealerId = u.getUserId();
					String toDealerId = mDealerBaseInfo.getId();

					System.out.println("currentDealerId==>" + currentDealerId
							+ ",toDealerId===" + toDealerId);
					HashMap<String, String> allParams = new HashMap<String, String>();

					allParams.put("fromDealersId", currentDealerId);
					allParams.put("toDealersId", toDealerId);

					Object o = utils.getWebservicesByData(
							ConstantUtils.NAME_SPACE,
							ConstantUtils.ALL_METHROD_NAME.get(36),
							ConstantUtils.NAME_SPACE
									+ ConstantUtils.ALL_METHROD_NAME.get(36),
							ConstantUtils.ATTENTION_TO_DEALERS_URL, allParams);

					Message msg = mHandler.obtainMessage();
					Bundle b = new Bundle();
					b.putString("success", o.toString());
					msg.setData(b);
					msg.obj = btn;
					msg.what = 1;
					// System.out.println("msg------->" + o);
					mHandler.sendMessage(msg);

				}
			}).start();

		}

		private void cancelAttentionDealer(final Button btn) {

			new Thread(new Runnable() {

				@Override
				public void run() {
					UserInfo u = (UserInfo) readObject("userInfo");

					String currentDealerId = u.getUserId();
					String toDealerId = mDealerBaseInfo.getId();

					System.out.println("currentDealerId==>" + currentDealerId
							+ ",toDealerId===" + toDealerId);
					HashMap<String, String> allParams = new HashMap<String, String>();

					allParams.put("fromDealersId", currentDealerId);
					allParams.put("toDealersId", toDealerId);

					Object o = utils.getWebservicesByData(
							ConstantUtils.NAME_SPACE,
							ConstantUtils.ALL_METHROD_NAME.get(37),
							ConstantUtils.NAME_SPACE
									+ ConstantUtils.ALL_METHROD_NAME.get(37),
							ConstantUtils.CANCEL_ATTENTION_TO_DEALERS_URL,
							allParams);

					Message msg = mHandler.obtainMessage();

					Bundle b = new Bundle();
					b.putString("success", o.toString());
					msg.setData(b);
					msg.obj = btn;
					msg.what = 2;
					System.out.println("msg------->" + o);
					mHandler.sendMessage(msg);

				}
			}).start();
		}
	}

	private boolean isAttentionDealer = true;
	private Handler mHandler = new Handler() {

		public void handleMessage(Message msg) {

			int what = msg.what;
			String dispMsg = "";
			Button btn = (Button) msg.obj;
			switch (what) {
			case 1:
				isAttentionDealer = false;
				dispMsg = "已成功收录到您关注的经销商列表";
				btn.setBackgroundResource(R.drawable.user_btn_4);
				break;

			case 2:
				isAttentionDealer = true;
				dispMsg = "已取消关注此经销商！";
				btn.setBackgroundResource(R.drawable.user_btn_3);
				break;
			}
			Bundle b = msg.getData();
			String m = b.getString("success");
			// String m = msg.obj.toString();
			if (m != null && (m.indexOf("操作成功") >= 0)) {
				Toast.makeText(getApplicationContext(), dispMsg,
						Toast.LENGTH_SHORT).show();

			} else {
				Toast.makeText(getApplicationContext(), "操作失败，请重试!",
						Toast.LENGTH_SHORT).show();

			}

		}
	};

	private class DealerMarketInfoTask extends
			AsyncTask<String, String, DealerBaseInfo> {

		@Override
		protected DealerBaseInfo doInBackground(String... params) {

			DealerBaseInfo d = null;
			if (utils.getAPNType(getApplicationContext()) == -1) {

				return null;
			} else {

				HashMap<String, String> allParams = new HashMap<String, String>();

				allParams.put("dealerId", params[0]);
				UserInfo u = (UserInfo) readObject("userInfo");
				allParams.put("nowUserId", u.getUserId());
				Object o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
						ConstantUtils.ALL_METHROD_NAME.get(5),
						ConstantUtils.NAME_SPACE
								+ ConstantUtils.ALL_METHROD_NAME.get(5),
						ConstantUtils.GET_DEALER_BY_DEALER_ID_URL, allParams);

				d = utils.parseBaseDealerInfo(o.toString(), true);
				System.out.println(d + "----");

				return d;

			}

		}

		@Override
		protected void onPreExecute() {

			progressBar.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(DealerBaseInfo result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			progressBar.setVisibility(View.GONE);
			if (result == null) {

				Toast.makeText(getApplicationContext(), "网络未连接，请设置网络!",
						Toast.LENGTH_SHORT).show();
			} else {

				// DealerInfoAdapter adapter = new DealerInfoAdapter(result);
				// list1.setAdapter(adapter);

				if (result instanceof DealerBaseInfo) {
					DealerMarketAdapter adapter = new DealerMarketAdapter(
							DealerMarketActivity.this, result);
					list1.setAdapter(adapter);
				}

			}

		}

	}

	private class DealerMarketDetailTask extends
			AsyncTask<String, String, ArrayList<Car>> {

		@Override
		protected ArrayList<Car> doInBackground(String... params) {
			if (utils.getAPNType(getApplicationContext()) == -1) {

				return null;
			} else {
				// GetCarsByDealerId(string dealerId,string nowPage,string
				// pageSize)

				HashMap<String, String> allParams = new HashMap<String, String>();

				allParams.put("dealerId", params[0]);
				allParams.put("nowPage", "1");
				allParams.put("pageSize", "20");
				Object o = utils.getWebservicesByData(ConstantUtils.NAME_SPACE,
						ConstantUtils.ALL_METHROD_NAME.get(4),
						ConstantUtils.NAME_SPACE
								+ ConstantUtils.ALL_METHROD_NAME.get(4),
						ConstantUtils.GET_CARS_BY_DEALER_ID, allParams);

				// System.out.println("oooo==" + o);
				ArrayList<Car> all = utils.parseJson(o.toString(), "table",
						NetworkProgressUtils.MY_PUBLISH_CAR_INFO_TYPE, false);
				// System.out.println("test===>"+o1);

				return all;

			}

		}

		@Override
		protected void onPreExecute() {

			progressBar.setVisibility(View.VISIBLE);
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(ArrayList<Car> result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			progressBar.setVisibility(View.GONE);
			if (result == null) {

				Toast.makeText(getApplicationContext(), "网络未连接，请设置网络!",
						Toast.LENGTH_SHORT).show();
			} else {

				// DealerInfoAdapter adapter = new DealerInfoAdapter(result);
				// list1.setAdapter(adapter);

				if ((result instanceof ArrayList) && result.size() > 0) {

					DealerMarket2Adapter adapter = new DealerMarket2Adapter(
							DealerMarketActivity.this, result);

					list2.setAdapter(adapter);

				}

			}

		}

	}

	private class DealerMarket2Adapter extends BaseAdapter {

		public DealerMarket2Adapter(Context mContext, ArrayList<Car> car) {

			this.mContext = mContext;
			this.car = car;
		}

		private Context mContext;
		private ArrayList<Car> car;

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return car.size();
		}

		@Override
		public Object getItem(int position) {

			return car.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {

				convertView = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.car_items, null);
			}

			Car c = car.get(position);

			if (c instanceof MyPublishCarInfo) {

				MyPublishCarInfo myPublishCarInfo = (MyPublishCarInfo) c;
				ImageView image = (ImageView) convertView
						.findViewById(R.id.itemCarImage);
				// 获取类型
				String type = myPublishCarInfo.getQhtime();
				if ("".equals(type)) {
					image.setImageResource(R.drawable.xianhuo);

				} else {
					image.setImageResource(R.drawable.qihuo);
				}
				// TextView typeText1 = (TextView) convertView
				// .findViewById(R.id.itemCarImage);
				// typeText1.setText(myPublishCarInfo.getXiliename());

				TextView typeText = (TextView) convertView
						.findViewById(R.id.itemType);
				typeText.setVisibility(View.VISIBLE);
				typeText.setText(myPublishCarInfo.getPinpainame() + "-"
						+ myPublishCarInfo.getXiliename());
				// TextView titleText = (TextView) convertView
				// .findViewById(R.id.itemTitle);
				//
				// titleText.setText(s.getPinpainame());
				// TextView abbreviationText = (TextView) convertView
				// .findViewById(R.id.itemAbbreviation);
				//
				// abbreviationText.setText(s.getName());
				// TextView typeText = (TextView) convertView
				// .findViewById(R.id.itemType);
				// typeText.setText(myPublishCarInfo.getXhorgh());
				// TextView titleText = (TextView) convertView
				// .findViewById(R.id.itemTitle);
				//
				// titleText.setText(myPublishCarInfo.getPinpainame());
				TextView abbreviationText = (TextView) convertView
						.findViewById(R.id.itemAbbreviation);

				abbreviationText.setText(myPublishCarInfo.getName());
				TextView priceText = (TextView) convertView
						.findViewById(R.id.itemPrice);

				priceText.setText(myPublishCarInfo.getPress() + "万");
				TextView configText = (TextView) convertView
						.findViewById(R.id.itemSelectConfig);

				configText.setText(myPublishCarInfo.getXppz());
				TextView publishText = (TextView) convertView
						.findViewById(R.id.itemPublishDate);

				String date = myPublishCarInfo.getAdddate();

				date = date.substring(0, date.indexOf(" ") + 1);
				publishText.setText(date);
				TextView dealerText = (TextView) convertView
						.findViewById(R.id.itemDealerName);
				dealerText.setText(myPublishCarInfo.getCompanyname());
			}

			convertView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			return convertView;

		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long id) {

		MyPublishCarInfo myPublishCarInfo = (MyPublishCarInfo) adapterView
				.getAdapter().getItem(position);

		// System.out.println("onItem=="+myPublishCarInfo.getName());
		Intent intent = new Intent();
		intent.setClass(this, CarDetailInfoActivity.class);
		intent.putExtra("cId", myPublishCarInfo.getId());
		String qTime = myPublishCarInfo.getQhtime();
		String carType = "";
		if (qTime.equals("")) {
			carType = "现货";
		} else {
			carType = "期货";
		}
		// System.out.println("test,,,,"+myPublishCarInfo.getXhorgh());
		// 传入车源的类型
		intent.putExtra("carType", carType);
		startActivity(intent);
	}
}
